import dayjs from "dayjs";
import { articleNormalCategory, ArticleNormalCategory } from "./data";
import { customAlphabet } from 'nanoid';

export const ossDomain = 'https://cdn.huihifi.com/';
export const completeImgUrl = (src?: string, param?: string) => {
  if(!src){
    return undefined;
  }
  let trueSrc = src;
  if (!/^http/.test(src)) {
    trueSrc = `${ossDomain}${src.replace(/\+/g, '%2B').replace(/#/g, '%23')}${param ? param : ''}`; // +号要特殊处理
  }
  return trueSrc;
};

// param 只能在只读场景下用
export const completeAllImgUrl = (src: string, raw?: boolean, param?: string) => {
  if (raw) {
    return src.replace(/"url":"(?!http|data:image)/g, str=>{
      return `${str}${ossDomain}`;
    });
  }
  return src.replace(/<img.*?src="((?!http|data:image).*?)"/g, (imgStr, prevSrc) => {
    return imgStr.replace(
      `src="${prevSrc}"`,
      `src="${ossDomain}${prevSrc}${param ? param : ''}"`
    );
  });
};

export const deleteAllImgUrl = (src: string, raw?: boolean) => {
  if(raw){
    return src.replace(new RegExp(`"url":"${ossDomain}`, 'g'), str=>{
      return str.replace(ossDomain, '');
    });
  }
  return src.replace(new RegExp(`<img.*?src="${ossDomain}`, 'g'), str=>{
    return str.replace(ossDomain, '');
  });
};

export const deleteEmptyField = (obj: any) => {
  if (obj) {
    const empty = [null, undefined, ''];
    Object.keys(obj).forEach((key) => {
      if (empty.includes(obj[key])) {
        // eslint-disable-next-line no-param-reassign
        delete obj[key];
      } else if (Array.isArray(obj[key])) {
        obj[key].forEach((item: any) => {
          if (item?.constructor === Object) {
            deleteEmptyField(item);
          }
        });
      } else if (obj[key].constructor === Object) {
        deleteEmptyField(obj[key]);
      }
    });
  }
};

export const getAllExtByLowerCase = (ext: string[])=>{
  return ext.concat(ext.map(item=>item.toUpperCase()));
}

export const getFileExtByName = (filename: string)=>{
  const lastIndex = filename.lastIndexOf('.');
  if(lastIndex === -1){
    return '';
  }
  return filename.substring(lastIndex + 1)
}

export const getFileTypeByName = (filename: string)=>{
  const ext = getFileExtByName(filename);
  if(['mp4'].includes(ext)){
    return 'video'
  }
  if(['jpeg', 'jpg','png','webp'].includes(ext)){
    return 'image'
  }
  return null
}

export const parseRadio = (num?: number | string)=>{
  if(num === undefined){
    return undefined;
  }
  return Number(num) / 100;
}

export const formatRadio = (num?: number)=>{
  return num !== undefined ? (num * 100) : undefined;
}


export function formatDateTime(time?: string | number){
  if(!time){
    return;
  }
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

export function formatMoney(amount?: number){
  if(amount === undefined || amount === null){
    return;
  }
  return amount.toLocaleString('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    currencyDisplay: 'symbol',
  })
}

export function formatArea(params?:{province: string;city:string;district: string}){
  if(!params?.province){
    return ''
  }
  return `${params.province}-${params.city !== params.province ? `${params.city}-` :''}${params.district}`;
}


export const csvStrToDataSet = (sourceData: string)=>{
  // console.log(JSON.stringify(sourceData));
  // 区别csv与另一种没有逗号的文本格式
  if (!sourceData.includes(',')) {
    sourceData = sourceData
      .replace(/[ \t]+/g, ',')
      // 如果是空格后面跟的括号的这种，就把逗号去掉还原回去，这里不是列分割的意思
      .replace(/,\(/g, '(');
  }
  const res= sourceData.replace(/\r/g, '').split('\n').map((item) => {
    return item.split(',');
  });
  // console.log(res);
  return res;
}

export const dataSetToCsv = (sourceDataSet: string[][])=>{
  return sourceDataSet.map(item=>item.join(',')).join('\n')
}

export const findNearestNumber = (arr: number[], target: number) => {
  let mid;
  let l = 0;
  let r = arr.length - 1;
  // 保证指针最终停留在相邻的两个数,所以这里是判断是否大于1
  while (r - l > 1) {
    mid = Math.floor((l + r) / 2);
    // 如果目标数比中间小，所以范围在左边
    if (target < arr[mid]) {
      r = mid;
    } else {
      l = mid;
    }
  }
  // 最后比较这两个数字的绝对差大小即可。
  return Math.abs(target - arr[l]) <= Math.abs(target - arr[r]) ? arr[l] : arr[r];
};

export const formatNumber = (numberStr: string) => {
  return numberStr ? Number(numberStr.trim()) : 0;
}

export const findNearestTargetRow = (dataSet: string[][], target: string) => {
  const xList: number[] = [];
  dataSet.forEach((row) => {
    //  判断这一行是不是数字，有可能是标题
    if (row[0] && !Number.isNaN(Number(row[0]))) {
      xList.push(formatNumber(row[0]));
    }
  });
  // console.log('target',target);
  const xValue = findNearestNumber(xList, Number(target));
  // console.log('xValue',xValue);
  return dataSet.find(item => formatNumber(item?.[0]) === xValue);
}

export const getRichTextArticleTitleCategoryPrefix = (category: ArticleNormalCategory)=>{
  return category ? `【${articleNormalCategory[category]}】` : '';
}

export const completeAllIframeUrl = (src: string) => {
  return src.replace(/<iframe.*?src="(?!http|data:image)/g, str=>{
    return `${str}${ossDomain}`;
  });
};

// 从富文本摘取图片list
export const getImgListFormRichText = (richText: string, length?: number)=> {
  const list: string[] = [];
  richText.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
    list.push(capture);
    return '';
  });
  return length ? list.slice(0, length) : list;
}

export const genTimeWithRandomStr = ()=>{
  return `${dayjs().format('YYYYMMDDHHmmss')}_${customAlphabet('0123456789', 6)()}`;
}

export const getFilenameByKey = (key: string)=>{
  const lastIndex = key.lastIndexOf('/');
  if(lastIndex === -1){
    return key;
  }
  return key.substring(lastIndex + 1)
}
